package org.elcom.sources;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

public class MD5 {

	//get MD5 from file at client
	public static String getMD5Checksum(String filename) throws Exception {
	     byte[] b = createChecksum(filename);
	     String result = "";
	     for (int i = 0; i < b.length; i++) {
	    	 result += Integer.toString((b[i] & 0xff ) + 0x100, 16).substring(1);
	     }
	     return result;
	   }

	private static byte[] createChecksum(String filename) throws Exception {
		// TODO Auto-generated method stub
		 InputStream fis =  new FileInputStream(filename);

	     byte[] buffer = new byte[1024];
	     MessageDigest complete = MessageDigest.getInstance("MD5");
	     int numRead;
	     do {
	    	 numRead = fis.read(buffer);
	    	 if (numRead > 0) {
	    		 complete.update(buffer, 0, numRead);
	    	 }
	     } while (numRead != -1);
	     fis.close();
	     return complete.digest();
	}
	//get MD5 from file on server
	public static String getDigest(InputStream is, MessageDigest md, int byteArraySize)	
		throws NoSuchAlgorithmException, IOException {

		md.reset();
		byte[] bytes = new byte[byteArraySize];
		int numBytes;
		while ((numBytes = is.read(bytes)) != -1) {
			md.update(bytes, 0, numBytes);
		}
		byte[] digest = md.digest();
		String result = new String(Hex.encodeHex(digest));
		return result;
	}
	
	//Check MD5 checksum
	public static boolean checkMD5(String pathServer, String pathClient) throws Exception{
		//Get MD5 File on server
		URL url = new URL(pathServer);
		InputStream is = url.openStream();
		MessageDigest md = MessageDigest.getInstance("MD5");
		String md5Server = MD5.getDigest(is, md, 2048);
//		System.out.println("	MD5 Server: " + md5Server + " File: " + pathServer);
		
		//Get MD5 File at Client
		String md5Client = MD5.getMD5Checksum(pathClient);
//		System.out.println("	MD5 Client: " + md5Client + " File: " + pathClient);

		//Check MD5
		if(md5Client.toString().equals(md5Server.toString())){
//			System.out.println("	File downloaded is the same with file on server ");
			return true;
		} else {
			System.out.println("	File downloaded is different with file on server \n\t\tRedownloading...");
			return false;
		}
	}
}
